#!/usr/bin/env python3
# -*- coding: utf-8 -*-

__author__ = 'cuihailong'

import logging
import asyncio
import aiomysql
from aiohttp import web

logging.basicConfig(level=logging.INFO)  # 指定日志级别为info


def log(sql, args=()):
    """
    用于记录执行的sql语句
    :param sql: sql语句
    :param args: 参数
    :return: 无
    """
    logging.info(f"SQL:{sql}")


async def create_pool(loop, **kw):
    """
    创建连接池
    我们需要创建一个全局的连接池，每个HTTP请求都可以从连接池中直接获取数据库连接。
    使用连接池的好处是不必频繁地打开和关闭数据库连接，而是能复用就尽量复用。
    连接池由全局变量__pool存储，缺省情况下将编码设置为utf8，自动提交事务：
    """
    logging.info('create database connection pool...')
    global __pool
    __pool = await aiomysql.create_pool(
        host=kw.get('host', 'localhost'),
        port=kw.get('port', 3306),
        user=kw.get('user'),
        password=kw.get('password'),
        db=kw.get('db'),
        charset=kw.get('charset', 'utf8'),
        autocommit=kw.get('autocommit', True),
        maxsize=kw.get('maxsize', 10),
        minsize=kw.get('minsize', 1),
        loop=loop
    )


async def select(sql, args, size=None):
    log(sql, args)  # 将执行的sql记录到日志中
    global __pool
    with (await __pool) as conn:
        cur = await conn.cursor(aiomysql.DictCursor)  # 创建游标
        await cur.execute(sql.replace('?', '%s'), args or ())  # sql占位符是？，MySQL占位符是%s，自动替换
        if size:
            # 如果获取指定记录条数，则获取指定记录条数；反之，则将所有记录返回
            records = await cur.fetchmany(size)
        else:
            records = await cur.fetchall()
        await cur.close()  # 关闭游标
        logging.info(f"rows returned:{len(records)}")
        return records


async def execute(sql, args):
    log(sql)
    with (await __pool) as conn:
        try:
            cur = await conn.cursor()
            await cur.execute(sql.replace('?', '%s'), args)
            affected = cur.rowcount  # 通过rowcount返回结果数
            await cur.close()
        except Exception as e:
            raise e
        return affected


def create_args_string(num):
    # 构造insert语句中values关键字后的sql语句
    L = []
    for n in range(num):
        L.append('?')
    return ', '.join(L)


class Field:

    def __init__(self, name, column_type, primary_key, default):
        self.name = name
        self.columu_type = column_type
        self.primary_key = primary_key
        self.default = default

    def __str__(self):
        return f"<{self.__class__.__name__}, {self.columu_type}:{self.name}"


class StringField(Field):
    def __init__(self, name=None, primary_key=False, default=None, ddl='varchar(100)'):
        super().__init__(name, ddl, primary_key, default)


class BooleanField(Field):
    def __init__(self, name=None, default=False):
        super().__init__(name, 'boolean', False, default)


class IntegerField(Field):
    def __init__(self, name=None, primary_key=False, default=0):
        super().__init__(name, 'bigint', primary_key, default)


class FloatField(Field):
    def __init__(self, name=None, primary_key=False, default=0.0):
        super().__init__(name, 'real', primary_key, default)


class TextField(Field):
    def __init__(self, name=None, default=None):
        super().__init__(name, 'text', False, default)


class ModelMetaclass(type):  # 创建元类，使用type
    def __new__(cls, name, bases, attrs):
        if name == 'Model':  # 排除Model这个类的本身
            return type.__new__(cls, name, bases, attrs)
        tableName = attrs.get('__table__', None) or name  # 获取表的名称
        logging.info(f'found model:{name}, table:{tableName}')
        maps = dict()
        fields = []
        primaryKey=None
        for k, v in attrs.items():
            if isinstance(v, Field):
                logging.info(f'found maps: {k} ==> {v}')
                maps[k] = v
                if v.primary_key:
                    if primaryKey:
                        raise RuntimeError(f'duplicate primary key for field:{k}')
                    primaryKey = k
                else:
                    fields.append(k)
        if not primaryKey:
            raise RuntimeError('Primary key not found.')
        for k in maps.keys():
            attrs.pop(k)
        escaped_fields = list(map(lambda f: f"`{f}`", fields))
        attrs['__maps__'] = maps  # 保存属性和列的对应关系
        attrs['__table__'] = tableName  # 表名
        attrs['__primary_key__'] = primaryKey  # 主键名
        attrs['__fields__'] = fields  # 除主键外的属性名
        # 默认构造select、insert、update、delete语句
        attrs['__select__'] = 'select `%s`, %s from `%s`' % (primaryKey, ', '.join(escaped_fields), tableName)
        attrs['__insert__'] = 'insert into `%s` (%s, `%s`) values (%s)' % (tableName, ', '.join(escaped_fields), primaryKey, create_args_string(len(escaped_fields) + 1))
        attrs['__update__'] = 'update `%s` set %s where `%s`=?' % (tableName, ', '.join(map(lambda f: '`%s`=?' % (maps.get(f).name or f), fields)), primaryKey)
        attrs['__delete__'] = 'delete from `%s` where `%s`=?' % (tableName, primaryKey)
        return type.__new__(cls, name, bases, attrs)

class Model(dict, metaclass=ModelMetaclass):

    def __init__(self, **kw):
        super(Model, self).__init__(**kw)

    def __getattr__(self, key):
        try:
            return self[key]
        except KeyError:
            raise AttributeError(f"'Model' object has no attribute {key}")

    def __setattr__(self, key, value):
        self[key] = value

    def getValue(self, key):
        return getattr(self, key, None)

    def getValueOrDefault(self, key):
        value = getattr(self, key, None)
        if value is None:
            field = self.__maps__[key]
            if field.default is not None:
                value = field.default() if callable(field.default) else field.default
                logging.debug(f"using default value for {key}:{str(value)}")
                setattr(self, key, value)
        return value

    @classmethod
    async def findAll(cls, where=None, args=None, **kw):
        # 查找所有符合条件的记录
        sql = [cls.__select__]
        if where:
            sql.append('where')
            sql.append(where)
        if not args:
            args = []
        orderBy = kw.get('orderBy', None)
        if orderBy:
            sql.append('order by')
            sql.append(orderBy)
        limit = kw.get('limit', None)
        if limit:
            sql.append('limit')
            if isinstance(limit, int):
                sql.append('?')
                args.append(limit)
            elif isinstance(limit, tuple) and len(limit) == 2:
                sql.append('?, ?')
                args.extend(limit)
            else:
                raise ValueError(f'Invalid limit value: {str(limit)}')
        records = await select(' '.join(sql), args)
        return [cls(**r) for r in records]

    @classmethod
    async def findNumber(cls, selectField, where=None, args=None):
        ' find number by select and where. '
        sql = [f'select {selectField} _num_ from {cls.__table__}']
        if where:
            sql.append('where')
            sql.append(where)
        records = await select(' '.join(sql), args, 1)
        if len(records) == 0:
            return None
        return records[0]['_num_']

    @classmethod
    async def find(cls, pk):
        ' find object by primary key. '
        records = await select(f'%s where `%s`=?' % (cls.__select__, cls.__primary_key__), [pk], 1)
        if len(records) == 0:
            return None
        return cls(**records[0])

    async def save(self):
        args = list(map(self.getValueOrDefault, self.__fields__))
        args.append(self.getValueOrDefault(self.__primary_key__))
        rows = await execute(self.__insert__, args)
        if rows != 1:
            logging.warning(f'failed to insert record: affected rows: {rows}')

    async def update(self):
        args = list(map(self.getValue, self.__fields__))
        args.append(self.getValue(self.__primary_key__))
        rows = await execute(self.__update__, args)
        if rows != 1:
            logging.warning(f'failed to update by primary key: affected rows: {rows}')

    async def remove(self):
        args = [self.getValue(self.__primary_key__)]
        rows = await execute(self.__delete__, args)
        if rows != 1:
            logging.warning(f'failed to remove by primary key: affected rows: {rows}')